package com.zbkj.common.core;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.tiangong.framework.bo.CDO;
import com.zbkj.common.utils.SpringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OssSms {

    @Value("${aliyun.sms.accessKeyId:}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret:}")
    private String accessKeySecret;
    @Value("${aliyun.sms.signName:}")
    private String signName;
    @Value("${aliyun.sms.templateCode:}")
    private String templateCode;


    public static OssSms getInstance() {
        OssSms bean = SpringUtil.getBean(OssSms.class);
        return bean;
    }
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public  Boolean sendSms(String testPhone, String name,Integer type) {
        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            client = createClient(
                    accessKeyId,accessKeySecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers(testPhone)
                .setSignName(signName)
               // .setTemplateCode("SMS_461775229")
                .setTemplateCode(templateCode)
                .setTemplateParam(new CDO().set("code",name).toString());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            if(sendSmsResponse.getStatusCode()==200){
                return true;
            }
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return false;
    }
}
